package com.msi.manning.network;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.widget.TextView;

public class Result extends Activity {
    private static final String CLASSTAG = Result.class.getSimpleName();

	public static final int MAIN_ID = Menu.FIRST;
    
    private TextView factof;
    private TextView calories;
    private TextView total_fat;
    private TextView sugar_tot;
    private TextView sodium;
    private TextView cholestrl;
    private TextView vitamin_c;
    private TextView protein;
    private TextView calcium;
    private String choice;
    
    @Override
    public void onCreate(final Bundle icicle) {
        super.onCreate(icicle);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        
        // inflate the SAME view XML layout file as ApacheHTTPWithAuth Activity (re-use it)
        this.setContentView(R.layout.result);
        
        this.factof 	= (TextView) findViewById(R.id.factof);
        this.calories 	= (TextView) findViewById(R.id.calories_val);
        this.total_fat 	= (TextView) findViewById(R.id.total_fat_val);
        this.sugar_tot 	= (TextView) findViewById(R.id.sugar_tot_val);
        this.sodium 	= (TextView) findViewById(R.id.sodium_val);
        this.cholestrl 	= (TextView) findViewById(R.id.cholestrl_val);
        this.vitamin_c 	= (TextView) findViewById(R.id.vitamin_c_val);
        this.protein 	= (TextView) findViewById(R.id.protein_val);
        this.calcium 	= (TextView) findViewById(R.id.calcium_val);


        Bundle extras = getIntent().getExtras();
        if (extras != null)
        	choice = extras.getString("choices");
        else
        	Log.d(Constants.LOGTAG, " " + Result.CLASSTAG + " Choice = " + choice);
        
            Log.e(Constants.LOGTAG, " " + Result.CLASSTAG + "No Choice passed");
        	
        final String url = "http://teamsupercool.x10hosting.com/result.php?keyword=" + choice;

        HashMap<String,String> facts = getHttpResponse(url);
        //HashMap<String,String> facts = new HashMap<String,String>();
        //facts.put("Energ_Kcal", "11");

        factof.setText(choice);
        if(facts.containsKey("Energ_Kcal"))
        	calories.setText(facts.get("Energ_Kcal") + " kcal");
        if(facts.containsKey("Tot_Fat"))
        	total_fat.setText(facts.get("Tot_Fat") + " g");
        if(facts.containsKey("Sugar_Tot"))
        	sugar_tot.setText(facts.get("Sugar_Tot") + " g");
        if(facts.containsKey("Sodium"))
        	sodium.setText(facts.get("Sodium") + " mg");
        if(facts.containsKey("Cholestrl"))
        	cholestrl.setText(facts.get("Cholestrl") + " mg");
        if(facts.containsKey("Vit_C"))
        	vitamin_c.setText(facts.get("Vit_C") + " mg");
        if(facts.containsKey("Protein"))
        	protein.setText(facts.get("Protein") + " g");
        if(facts.containsKey("Calcium"))
        	calcium.setText(facts.get("Calcium") + " mg");
    }
    
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        boolean result = super.onCreateOptionsMenu(menu);
        menu.add(0, MAIN_ID, 0, R.string.menu_main);
        return result;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch (item.getItemId()) {
        case MAIN_ID:
            startActivity(new Intent(Result.this, NutritionMe.class));
            return true;
        }
       
        return super.onOptionsItemSelected(item);
    }
    
    /**
     * Perform an HTTP GET with HttpUrlConnection.
     * 
     * @param location
     * @return
     */
    private HashMap<String,String> getHttpResponse(String location) {
        URL url = null;
        HashMap<String, String> items = new HashMap<String, String>();
        
        Log.d(Constants.LOGTAG, " " + Result.CLASSTAG + " location = " + location);

        try {
            url = new URL(location);
            Log.d(Constants.LOGTAG, " " + Result.CLASSTAG + " url = " + url);
        } catch (MalformedURLException e) {
            Log.e(Constants.LOGTAG, " " + Result.CLASSTAG + " " + e.getMessage());
        }

        if (url != null) {

           // this.progressDialog = ProgressDialog.show(this, "working . . .", "performing HTTP request");
        
        	
        	try 
        	{
                HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
                BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
                String inputLine = "";
                
		/*
                char a;
                while ((a = (char) in.read()) != -1)
                	inputLine += a;*/
                String x;
                while ((x = in.readLine()) != null)
                	inputLine += x;
                
                if (!inputLine.startsWith("Shrt_Desc"))
                	throw new IOException("Nutritional Value is currently unavailable");
                
                // split
                String[] result = new String[24];
                String[] inputs0 = inputLine.split("Shrt_Desc:");
                result[0] = "Shrt_Desc";
                String temp = inputs0[1];
                String[] inputs1 = temp.split("Energ_Kcal:");
                result[1] = inputs1[0];
                result[2] = "Energ_Kcal";
                temp = inputs1[1];
                String[] inputs2 = temp.split("Tot_Fat:");
                result[3] = inputs2[0];
                result[4] = "Tot_Fat";
                temp = inputs2[1];
                String[] inputs3 = temp.split("FA_Sat:");
                result[5] = inputs3[0];
                result[6] = "FA_Sat";
                temp = inputs3[1];
                String[] inputs4 = temp.split("Cholestrl:");
                result[7] = inputs4[0];
                result[8] = "Cholestrl";
                temp = inputs4[1];
                String[] inputs5 = temp.split("Sodium:");
                result[9] = inputs5[0];
                result[10] = "Sodium";
                temp = inputs5[1];
                String[] inputs6 = temp.split("Carbohydrt:");
                result[11] = inputs6[0];
                result[12] = "Carbohydrt";
                temp = inputs6[1];
                String[] inputs7 = temp.split("Sugar_Tot:");
                result[13] = inputs7[0];
                result[14] = "Sugar_Tot";
                temp = inputs7[1];
                String[] inputs8 = temp.split("Fiber_TD:");
                result[15] = inputs8[0];
                result[16] = "Fiber_TD";
                temp = inputs8[1];
                String[] inputs9 = temp.split("Protein:");
                result[17] = inputs9[0];
                result[18] = "Protein";
                temp = inputs9[1];
                String[] inputs10 = temp.split("Vit_C:");
                result[19] = inputs10[0];
                result[20] = "Vit_C";
                temp = inputs10[1];
                String[] inputs11 = temp.split("Calcium:");
                result[21] = inputs11[0];
                result[22] = "Calcium";
                result[23] = inputs11[1];
                
                for (int i = 0; i < result.length; i+=2)
                {
                	Log.v(Constants.LOGTAG, " " + Result.CLASSTAG + " inputLine = " + result[i] + result[i + 1]);
                	items.put(result[i],result[i+1]);
                }

                in.close();
                urlConn.disconnect();

            } catch (IOException e) {
                Log.e(Constants.LOGTAG, " " + Result.CLASSTAG + " " + e.getMessage());
            }

            //this.progressDialog.dismiss();
        } else {
            Log.e(Constants.LOGTAG, " " + Result.CLASSTAG + " url NULL");
        }
        return items;
    }
    
}
